<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table
      :data="pageInfo.pageList"
      highlight-current-row
      v-loading="listLoading"
      @selection-change="selsChange"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column type="index" width="60"> </el-table-column>
      <el-table-column prop="name" label="部门" width="120" sortable>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" sortable>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="180" sortable>
      </el-table-column>
      <el-table-column
        prop="manager.username"
        label="部门经理"
        width="120"
        sortable
      >
      </el-table-column>
      <el-table-column prop="parent.name" label="上级" width="120" sortable>
      </el-table-column>
      <el-table-column prop="path" label="path" width="80" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="80" sortable>
        <template scope="scope">
          <p v-if="scope.row.state == 1" style="color: green">启用</p>
          <p v-else style="color: red">禁用</p>
        </template>
      </el-table-column>
      <el-table-column prop="intro" label="描述" min-width="180" sortable>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="small"
            @click="handleDel(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button
        type="danger"
        @click="batchRemove"
        :disabled="this.sels.length === 0"
        >批量删除</el-button
      >
      <!-- <el-pagination
        layout="prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
				:page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        :total="pageInfo.count"
        style="float: right"
      >
      </el-pagination> -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="query.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.count"
        style="float: right"
      >
      </el-pagination>
    </el-col>

    <!--新增界面-->
    <el-dialog
      title="新增"
      :visible.sync="addFormVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="addForm"
        label-width="80px"
        :rules="addFormRules"
        ref="addForm"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="管理员">
          <!-- <el-input v-model="addForm.manager.id" ></el-input> -->
          <el-select
            v-model="addForm.manager"
            clearable
            value-key="id"
            placeholder="请选择"
          >
            <!--下拉选项
						  :key=""  //唯一标识
						  :label 选择之后展示到选择框中的值
						  :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
						     必须要写  value-key="id"
						-->
            <el-option
              v-for="item in employees"
              :key="item.id"
              :label="item.username"
              :value="item"
            >
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.email
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="父部门">
          <!-- <el-input v-model="addForm.parent.id"></el-input> -->
          <el-cascader
            v-model="addForm.parent"
            :options="deptTree"
            :props="{
              checkStrictly: true,
              label: 'name',
              value: 'id',
            }"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="addForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="addForm.intro"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click.native="addSubmit"
          :loading="addLoading"
          >提交</el-button
        >
      </div>
    </el-dialog>
    
  </section>
</template>

<script>
export default {
  data() {
    return {
      filters: {
        name: '',
      },
      users: [],
      pageInfo: {
        count: 0,
        pageList: [],
      },
      query: {
        page: 1,
        pageSize: 10,
      },
      listLoading: false,
      sels: [], //列表选中列

      addFormVisible: false, //新增界面是否显示
      addLoading: false,
      addFormRules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
      },
      //新增界面数据
      addForm: {
        id: '',
        name: '',
        intro: '',
        manager: {
          id: '',
          username: '',
        },
        parent: {
          id: '',
          name: '',
        },
        state: 0,
        path: '',
      },
      // 所有员工-用于选择管理员
      employees: [],
      deptTree: [],
    }
  },
  methods: {
    search() {
      this.query.page = 1
      this.getDepartments()
    },
    //性别显示转换
    formatSex: function (row, column) {
      return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知'
    },
    handleSizeChange(val) {
      this.query.pageSize = val
      this.query.page = 1
      this.getDepartments()
    },
    handleCurrentChange(val) {
      this.query.page = val
      this.getDepartments()
    },
    //获取部门列表
    getDepartments() {
      let para = {
        currentPage: this.query.page,
        pageSize: this.query.pageSize,
        keyword: this.filters.name,
      }
      // this.listLoading = true;
      //NProgress.start();
      this.$http.post('/department', para).then((res) => {
        console.log('结果', res.data.data)
        this.pageInfo = res.data.data
      })
      // getUserListPage(para).then((res) => {
      // 	this.total = res.data.total;
      // 	this.users = res.data.users;
      // 	this.listLoading = false;
      // 	//NProgress.done();
      // });
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning',
      })
        .then(() => {
          this.listLoading = true
          this.$http.delete('/department/' + row.id).then((res) => {
            if (res.data.success) {
              this.$message.success('删除成功')
              this.listLoading = false
              this.query.page = 1
              this.getDepartments()
            } else {
              this.$message.error(res.data.message)
            }
          })
        })
        .catch(() => {
          this.$message.error('网络异常')
        })
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.getAllEmp()
      this.getTree()
      this.addFormVisible = true
      this.addForm = Object.assign({}, row)
      if (!this.addForm.parent) {
        this.addForm.parent = {
          id: '',
          name: '',
        }
      }
      if (!this.addForm.manager) {
        this.addForm.manager = {
          id: '',
          username: '',
        }
      }
    },
    //显示新增界面
    handleAdd: function () {
      this.getAllEmp()
      this.getTree()
      this.addFormVisible = true
      this.addForm = {
        id: '',
        name: '',
        intro: '',
        manager: {
          id: '',
          username: '',
        },
        parent: {
          id: '',
          name: '',
        },
        state: 0,
        path: '',
      }
    },
    // 查询所有员工
    getAllEmp() {
      this.$http.get('/employee').then((res) => {
        res = res.data
        this.employees = res.data
      })
    },
    // 查询部门树
    getTree() {
      this.$http
        .get('/department/tree')
        .then((res) => {
          res = res.data
          if (res.success) {
            this.deptTree = res.data
            if (this.addForm.path != null && this.addForm.path != '') {
              var path = this.addForm.path.split('/')
              console.log('path', path)
              var list = []
              for (let i = 1; i < path.length - 1; i++) {
                list.push(parseInt(path[i]))
              }

              this.addForm.parent = list
              console.log(list)
            } else {
              this.addForm.parent = null
            }
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(() => {
          this.$message.error('网络错误')
        })
    },
    //新增
    addSubmit: function (index, row) {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = false
            //NProgress.start();
            let para = Object.assign({}, this.addForm)
            if (para.parent != null && para.parent != '') {
              for (let index = 0; index < para.parent.length; index++) {
                this.addForm.parent = {
                  id: para.parent[index],
                }
              }
            } else {
              this.addForm.parent = {
                id: '',
              }
            }
            
            if (para.manager == null || para.manager == '') {
              this.addForm.manager = {
                id: '',
                username: '',
              }
            }
            console.log("管理员数据",this.addForm);

            console.log('数据', this.addForm)
            this.$http
              .put('/department', this.addForm)
              .then((res) => {
                this.addLoading = false
                res = res.data
                if (res.success) {
                  this.$message.success('更新成功')
                  this.addFormVisible = false
                  this.search()
                } else {
                  this.$message.error(res.message)
                }
              })
              .catch(() => {
                this.$message.error('网络错误')
              })
          })
        }
      })
    },
    selsChange: function (sels) {
      this.sels = sels
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map((item) => item.id)
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning',
      })
        .then(() => {
          this.listLoading = true
          this.$http.patch('/department', ids).then((res) => {
            if (res.data.success) {
              this.$message.success('批量删除成功')
              this.listLoading = false
              this.query.page = 1
              this.getDepartments()
            } else {
              this.$message.error(res.data.message)
            }
          })
        })
        .catch(() => {
          this.$message.error('网络异常')
        })
    },
  },
  mounted() {
    this.getDepartments()
  },
}
</script>

<style scoped></style>
